// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database();
  let course = event.key
  let data = event.data
  let start = new Date(data.start_time)
  let end = new Date(data.end_time)
  let isSelf = event.isSelf

  let res;
  let prefix = isSelf ? 'self.' + course : course
  let params = {
    [prefix]: {
      start_time: start,
      end_time: end,
      duration: ~~((end - start) / 1000 / 60)
    }
  }

  try {
    res = await db.collection("tb_schedule").where({
      date: new Date().toLocaleDateString().replace(/\//g, '-'),
      _openid: wxContext.OPENID
    }).update({
      data: params
    })
  } catch (e) {
    return e
  }
  return res
}